package cn.wqb.bpp.common.utils.task;

public class Task {

    protected TaskQueue taskQueue;

    private boolean hasStarted;
    private boolean hasFinished;
    private int repeatTimes;
    private boolean threadRun;

    public Task(TaskQueue taskQueue, int repeatTimes) {
        this.taskQueue = taskQueue;
        this.repeatTimes = repeatTimes;
    }

    public void startWork() {
        if (!hasStarted) {
            hasStarted = true;
            hasFinished = false;
            threadRun = true;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < repeatTimes; i++) {
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (!threadRun) {
                            break;
                        }
                        work();
                    }
                    onWorkFinish(false);
                }
            }).start();
        }
    }

    protected void work() {
    }

    protected void onWorkFinish(boolean taskSucceed) {
        if(!hasFinished){
            hasFinished = true;
            threadRun = false;
            if (taskQueue.workingPool.contains(this)) {
                taskQueue.workingPool.remove(this);
            }
            Task nextTask = taskQueue.queue.poll();
            if (nextTask != null) {
                taskQueue.workingPool.add(nextTask);
                nextTask.startWork();
            }
        }
    }

}
